package com.yjc.drygoods.member.exception;

import com.yjc.common.exception.BizCodeEnume;
import com.yjc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yjc
 * @create 2022-08-28 22:56
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.yjc.drygoods.member"})
public class DryGoodsExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R VaildHandleException(MethodArgumentNotValidException e) {
        log.error("异常信息：{}，异常类型：{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item) -> {
            map.put("msg", item.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCodeException(), BizCodeEnume.VAILD_EXCEPTION.getMessageException()).put("data", map);
    }

    @ExceptionHandler(value = CodeNotRightException.class)
    public R CodeNotRightException(CodeNotRightException e) {
        log.error("异常信息：{}，异常类型：{}", e.getMessage(), e.getClass());
        Map<String, String> map = new HashMap<>();
        map.put("msg", e.getMessage());
        return R.error().setData(map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R HandleException(Throwable e) {
        log.error("异常信息：{}，异常类型：{}", e.getMessage(), e.getClass());
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCodeException(), BizCodeEnume.UNKNOW_EXCEPTION.getMessageException());
    }
}
